package com.zhentao.config;

import com.zhentao.service.ParamCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 缓存预热配置
 * 
 * @author zhentao
 * @date 2024-12-19
 */
@Slf4j
@Component
@Order(1000) // 确保在其他组件初始化后执行
@ConditionalOnProperty(name = "param.cache.warmup.enabled", havingValue = "true", matchIfMissing = true)
public class CacheWarmupConfig implements CommandLineRunner {

    @Autowired
    private ParamCacheService paramCacheService;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始执行缓存预热...");
        
        try {
            // 检查缓存服务是否健康
            if (!paramCacheService.isHealthy()) {
                log.warn("缓存服务不健康，跳过预热");
                return;
            }
            
            // 执行缓存预热
            paramCacheService.warmUpCache();
            
            // 输出缓存统计信息
            var stats = paramCacheService.getCacheStatistics();
            log.info("缓存预热完成，统计信息: {}", stats);
            
        } catch (Exception e) {
            log.error("缓存预热失败", e);
        }
    }
}
